package com.jxl.springboot.game.service;

import com.jxl.springboot.game.mapper.UserMapper;
import com.jxl.springboot.game.pojo.User;
import com.jxl.springboot.game.pojo.UserLoginRecord;
import com.jxl.springboot.game.utils.IPUtils;
import com.jxl.springboot.game.utils.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 用户业务
 *
 * @author 江雪林
 * @create 2021-03-29
 */
@Service
public class UserService {
    @Autowired(required = false)
    private UserMapper userMapper;
    @Autowired
    private UserLoginRecordService userLoginRecordService;

    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    public int login(String username, String password) throws IOException {
        if (username != null || password != null) {
            User user = userMapper.login(username, password);
            if (user != null) {
                //添加用户登录记录
                UserLoginRecord record = new UserLoginRecord(user.getId(), null);
                //如果这里添加失败，需要使用消息队列来实现，先不做处理
                userLoginRecordService.addRecord(record);
                return user.getId();
            }
        }
        return -1;
    }

    /**
     * 用户名是否存在
     *
     * @param username
     * @return
     */
    public boolean UserNameIsExsist(String username) {
        if (username != null) {
            return userMapper.findCountByUserName(username) > 0;
        }
        return false;
    }

    /**
     * 注册
     *
     * @param user
     * @return
     */
    public boolean register(User user) throws IOException {
        if (user != null) {
            if (user.getUsername() != null && user.getPassword() != null) {
                if (!this.UserNameIsExsist(user.getUsername())) {
                    //设置默认权限
                    user.setRole("dev");
                    //模拟前端对密码进行加密
                    user.setPassword(Md5Utils.MD5Lower(user.getPassword()));
                    if (userMapper.register(user) > 0) {
                        return true;
                    }
                } else {
                    return false;
                }
            }
        }
        return false;
    }

    /**
     * 获取用户权限
     * @param uid
     * @return
     */
    public String getUserRole(Integer uid){
        if (uid!=null && uid>0){
            return userMapper.findRoleByUid(uid);
        }
        return null;
    }
}
